package com.holyn.guofang.view.Login;

import android.app.Activity;
import android.content.ContentProvider;
import android.content.Intent;
import android.support.annotation.IdRes;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.holyn.guofang.R;
import com.holyn.guofang.model.webhttp.HttpConfigure;
import com.holyn.guofang.model.webhttp.wo.StatusWo;
import com.holyn.guofang.presenter.BaseView;
import com.holyn.guofang.presenter.login.RegisterContract;
import com.holyn.guofang.presenter.login.RegisterPresenter;
import com.holyn.guofang.utils.MD5Uitl;
import com.holyn.guofang.utils.ValidUtil;
import com.holyn.guofang.view.BaseActivity;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Holyn on 2017/6/8.
 */

public class RegisterActivity extends BaseActivity implements BaseView, RegisterContract.View {

    private static final int REQUEST_ACTION_REGISTER = 0x0001;
    private static final int REQUEST_ACTION_VALIDE_CODE = 0x0002;

    public static final String INTENT_KEY_USER_NAME = "INTENT_KEY_USER_NAME";
    public static final String INTENT_KEY_PASSWORD = "INTENT_KEY_PASSWORD";

    @BindView(R.id.rb_main_mobile)
    RadioButton rbMainMobile;
    @BindView(R.id.rb_sub_mobile)
    RadioButton rbSubMobile;
    @BindView(R.id.rg_register_type)
    RadioGroup rgRegisterType;
    @BindView(R.id.ll_main_mobile)
    LinearLayout llMainMobile;
    @BindView(R.id.et_main_mobile)
    EditText etMainMobile;
    @BindView(R.id.et_mobile)
    EditText etMobile;
    @BindView(R.id.et_validCode)
    EditText etValidCode;
    @BindView(R.id.cb_is_read)
    CheckBox cbIsRead;
    @BindView(R.id.tv_provision)
    TextView tvProvision;
    @BindView(R.id.tv_register_submit)
    TextView tvRegisterSubmit;
    @BindView(R.id.tv_get_register_code)
    TextView tvGetRegisterCode;

    private RegisterContract.Presenter registerPresenter;

    Disposable disposable = null;//发送验证码倒计时控制

    public static void startForResult(Activity activity, int requestCode){
        Intent intent = new Intent(activity, RegisterActivity.class);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_register_2;
    }

    @Override
    protected void onMyCreate() {
        ButterKnife.bind(this);
        showToolbar("用户注册");
        registerPresenter = new RegisterPresenter(this);
        registerPresenter.addViewListener(this);
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        setTvGetRegisterCodeFinish();
    }

    private void initView() {

        rgRegisterType.setOnCheckedChangeListener((radioGroup, i) -> {
            switch (i) {
                case R.id.rb_main_mobile:
                    llMainMobile.setVisibility(View.GONE);
                    break;

                case R.id.rb_sub_mobile:
                    llMainMobile.setVisibility(View.VISIBLE);
                    break;
            }
        });

    }

    @OnClick({R.id.et_validCode, R.id.tv_provision, R.id.tv_register_submit, R.id.tv_get_register_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_validCode:
                break;
            case R.id.tv_provision:
                break;
            case R.id.tv_get_register_code:
                submitRegisterCode();
                break;
            case R.id.tv_register_submit:
                submitRegister();
                break;
        }
    }

    @Override
    public void requestStart(Integer requestAction) {
        switch (requestAction) {
            case REQUEST_ACTION_REGISTER:
            case REQUEST_ACTION_VALIDE_CODE:
                showLoadingDialog();
                break;
        }
    }

    @Override
    public void requestError(Integer requestAction, Throwable e) {
        closeLoadingDialog();
    }

    @Override
    public void requestComplete(Integer requestAction) {
        closeLoadingDialog();
    }

    @Override
    public void responseSuccess(Integer requestAction, StatusWo statusWo) {
        switch (requestAction) {
            case REQUEST_ACTION_REGISTER:
                if (statusWo.getStatus() == HttpConfigure.STATUS_SUCCESS) {
                    toastMsg("注册成功");
                    Intent intent = getIntent();
                    intent.putExtra(INTENT_KEY_USER_NAME, etMobile.getText().toString().trim());
//                    intent.putExtra(INTENT_KEY_PASSWORD, etPassword.getText().toString().trim());
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                } else {
                    toastMsg(statusWo.getStatus()+" - "+statusWo.getErr());
                }
                break;
            case REQUEST_ACTION_VALIDE_CODE:
                if (statusWo.getStatus() == HttpConfigure.STATUS_SUCCESS) {
                    toastMsg("发送验证码成功");
                } else {
                    toastMsg(statusWo.getStatus()+" - "+statusWo.getErr());
                    setTvGetRegisterCodeFinish();
                }
                break;
        }
    }

    private void submitRegisterCode() {
        String userName = etMobile.getText().toString();
        String equipmentCode = etMobile.getText().toString();
        if (!ValidUtil.isTelephone(equipmentCode)) {
            showToastDialog("请输入正确的电话号码");
            return;
        }
        startCountTimeView(60);
        registerPresenter.postRegisterCodeB(userName, equipmentCode, REQUEST_ACTION_VALIDE_CODE);
    }

    private void submitRegister() {
        Integer regType = 1;
        String mainMobile = "";
        String mobile = "";
        String validCode = "";
        Integer isInstitution = 0;

        if (rbMainMobile.isChecked()) {
            regType = 1;
        } else {
            regType = 2;
            mainMobile = etMainMobile.getText().toString().trim();
            if (!ValidUtil.isTelephone(mainMobile)) {
                showToastDialog("请输入正确的附属主号");
                return;
            }
        }

        mobile = etMobile.getText().toString().trim();
        if (!ValidUtil.isTelephone(mobile)) {
            showToastDialog("请输入正确的手机号码");
            return;
        }

        validCode = etValidCode.getText().toString();
        if (TextUtils.isEmpty(validCode)) {
            showToastDialog("请输入验证码");
            return;
        }

        if (!cbIsRead.isChecked()) {
            showToastDialog("请阅读并同意《服务条款》");
            return;
        }

        registerPresenter.postRegisterB(regType, mainMobile, mobile, validCode, isInstitution, REQUEST_ACTION_REGISTER);
    }

    /**
     * 倒计时
     */
    protected void startCountTimeView(final int countTime){
        setTvGetRegisterCodeBegin(countTime);
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(countTime + 1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Function<Long, Integer>() {
                    @Override
                    public Integer apply(@NonNull Long aLong) throws Exception {
                        return countTime - aLong.intValue();
                    }
                })
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        RegisterActivity.this.disposable = disposable;
                    }
                })
                .doOnNext(new Consumer<Integer>() {
                    @Override
                    public void accept(@NonNull Integer integer) throws Exception {
                        tvGetRegisterCode.setText(String.valueOf(integer)+"s");
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        setTvGetRegisterCodeFinish();
                    }
                }).subscribe();
    }

    private void setTvGetRegisterCodeBegin(int countTime) {
        tvGetRegisterCode.setBackgroundColor(ContextCompat.getColor(RegisterActivity.this, R.color.gray));
        tvGetRegisterCode.setText(String.valueOf(countTime)+"s");
        tvGetRegisterCode.setClickable(false);

    }

    private void setTvGetRegisterCodeFinish() {
        if (disposable != null){
            disposable.dispose();
        }
        tvGetRegisterCode.setBackgroundColor(ContextCompat.getColor(RegisterActivity.this, R.color.colorPrimaryDark));
        tvGetRegisterCode.setText("获取验证码");
        tvGetRegisterCode.setClickable(true);
    }

}
